package com.gsmvn.ngamgaixinh;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.appota.congaixinh.model.Banner;
import com.appota.congaixinh.model.Image;
import com.appota.congaixinh.model.Photo;
import com.appota.vn.network.HttpHelper;
import com.appota.vn.social.common.CommonStatic;
import com.appota.vn.util.CommonUtils;
import com.appota.vn.util.TimeComparator;
import com.facebook.FacebookException;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Request.Callback;
import com.facebook.Request.GraphUserCallback;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.OnErrorListener;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

public class MainActivity extends Activity {
	public static final String GOOGLE_LINK = "https://play.google.com/store/search?q=pub:GSMVN";
	public static final String FB_CONGAIXINH_ALBUM_ID = "120045928076226";
	private static final String TRACKER_ID = "UA-37513871-5";
	private Tracker tracker;
	HackyViewPager viewPager;
	ArrayList<Photo> photos = new ArrayList<Photo>();
	String paging;
	int[] fbOffset ;
	Menu menu;
	LinearLayout ll_loading;
	ImageView imgBanner;
	RelativeLayout llBanner;
	ImageView btnCloseBanner;
	UiLifecycleHelper uiLifecycleHelper;
	boolean isShowNetworkDialog = false;
	boolean useFullscreen = false;
	boolean isShowNavButton = true;
	Banner banner;
	Banner popup;
	boolean isShowPopup = false;
	GraphUser graphUser;
	String accestoken;

	boolean is_add_temp_photo = false;
	public static final int alarm_interval = 10*60*60* 1000;

	public static final int alarm_floating_interval = 10*60*60* 1000;

	boolean isFistRequest = false;

	public boolean isFBActive() {
		Session session = Session.getActiveSession();
		if (session == null) {
			return false;
		}
		return session.isOpened();
	}

	private DisplayImageOptions options;
	private ImageLoader imageLoader;
	private DataSource datasource;
	private AlertDialog dialog;
	protected PagerAdapter adapter;
	private String apk_name = "ConGaiXinh_v1.0.apk";
	private Long update_time_value;

	private void initListPhoto(Response response) {
		Gson gson = new Gson();
		try {
			GraphObject graphObject = response.getGraphObject();
			if (graphObject != null) {
				JSONObject grap = graphObject.getInnerJSONObject();
				JSONArray array = grap.getJSONArray("data");
				if (array.length() > 0) {
					int[] object_counts = new int[CommonStatic.arr.length];
					int object_count=0;
					Log.e("", "array lenght"+ array.length());
					for (int i = 0; i < object_counts.length; i++) {
						object_counts[i] = array.getJSONObject(i)
								.getJSONArray("fql_result_set").length();
						object_count+=object_counts[i];
					}
					int temp = photos.size();
					if (photos.size() < 100) {
						for (int i = 0; i < object_count; i++) {
							Photo photo = new Photo();
							photos.add(photo);
						}
					} else if (photos.size() > 100) {
						Log.e("", "photo size " + photos.size());
						temp = photos.size() - 1;
						for (int i = 0; i < object_count - 1; i++) {
							Photo photo = new Photo();
							photos.add(photo);
						}
					}
					Log.e("", "photo size after add " + photos.size());
					for (int i = 0; i < array.length(); i++) {
						JSONObject object = array.getJSONObject(i);
						String nameobject = object.getString("name");
						JSONArray fqlresult = object
								.getJSONArray("fql_result_set");
						if (nameobject.equals("photos" + CommonStatic.arr[0])) {
							int temp_photo_count = fqlresult.length();
							if (temp_photo_count == 25) {
								for (int j = 0; j < temp_photo_count; j++) {
									JSONObject object1 = fqlresult
											.getJSONObject(j);
									if (j == 0) {
										String update_time = object1
												.getString("created");
										update_time_value = Long
												.valueOf(update_time);
									}
									ArrayList<Image> images = new ArrayList<Image>();
									JSONArray imgArray = object1
											.getJSONArray("images");
									for (int k = 0; k < imgArray.length(); k++) {
										JSONObject object2 = imgArray
												.getJSONObject(k);
										Image image = gson
												.fromJson(object2.toString(),
														Image.class);
										// Log.d("image", "image Link " +
										// image.getSource());
										images.add(image);
									}
									String link = object1.getString("link");
									photos.get(j + temp).setLink(link);
									String caption = object1
											.getString("caption");
									for (String string : CommonStatic.avoid_strings) {
										if (caption.contains(string)) {
											Log.e("",
													"apear need dellete string "
															+ string
															+ "  delete them ");
											caption = caption.replace(string,
													"");
										}
									}
									Log.e("", "caption " + caption);
									String photo_id = object1
											.getString("object_id");

									Log.e("", "photo_id " + photo_id);
									if (datasource.isOpen())
										if (datasource.isAvailable(String
												.valueOf(photo_id)))
											photos.get(j + temp).isFavorite = true;
									photos.get(j + temp).setId(
											String.valueOf(photo_id));
									photos.get(j + temp).setName(caption);
									photos.get(j + temp).setImages(images);
									int created = object1.getInt("created");
									photos.get(j + temp).setCreated(created);
									String album_id = object1
											.getString("album_object_id");
									photos.get(j + temp).setAlbum_object_id(
											album_id);

								}
							} else {
								fbOffset[0] = -1;
							}
						} else if (nameobject.equals("photos"
								+ CommonStatic.arr[1])) {
							int temp_photo_count = fqlresult.length();
							if (temp_photo_count == 25) {
								for (int j = 0; j < temp_photo_count; j++) {
									JSONObject object1 = fqlresult
											.getJSONObject(j);
									if (j == 0) {
										String update_time = object1
												.getString("created");
										if (Long.valueOf(update_time) > update_time_value) {
											update_time_value = Long
													.valueOf(update_time);
										}
									}
									ArrayList<Image> images = new ArrayList<Image>();
									JSONArray imgArray = object1
											.getJSONArray("images");
									for (int k = 0; k < imgArray.length(); k++) {
										JSONObject object2 = imgArray
												.getJSONObject(k);
										Image image = gson
												.fromJson(object2.toString(),
														Image.class);
										// Log.d("image", "image Link " +
										// image.getSource());
										images.add(image);
									}
									String link = object1.getString("link");
									photos.get(j + object_counts[0] + temp)
											.setLink(link);
									String caption = object1
											.getString("caption");
									String photo_id = object1
											.getString("object_id");
									for (String string : CommonStatic.avoid_strings) {
										if (caption.contains(string)) {
											caption = caption.replace(string,
													"");
										}
									}
									Log.e("", "caption " + caption);
									Log.e("", "photo_id " + photo_id);
									if (datasource.isOpen())
										if (datasource.isAvailable(String
												.valueOf(photo_id)))
											photos.get(j + object_counts[0] + temp).isFavorite = true;
									photos.get(j + object_counts[0] + temp).setId(
											String.valueOf(photo_id));
									photos.get(j + object_counts[0] + temp)
											.setName(caption);
									photos.get(j + object_counts[0] + temp)
											.setImages(images);
									int created = object1.getInt("created");
									photos.get(j + object_counts[0] + temp)
											.setCreated(created);
									String album_id = object1
											.getString("album_object_id");
									photos.get(j + object_counts[0] + temp)
											.setAlbum_object_id(album_id);

								}
							} else {
								fbOffset[1] = -1;
							}
						} else if (nameobject.equals("photos"
								+ CommonStatic.arr[2])) {
							int temp_photo_count = fqlresult.length();
							if (temp_photo_count == 25) {
								for (int j = 0; j < temp_photo_count; j++) {
									JSONObject object1 = fqlresult
											.getJSONObject(j);
									if (j == 0) {
										String update_time = object1
												.getString("created");
										if (Long.valueOf(update_time) > update_time_value) {
											update_time_value = Long
													.valueOf(update_time);
										}
									}
									ArrayList<Image> images = new ArrayList<Image>();
									JSONArray imgArray = object1
											.getJSONArray("images");
									for (int k = 0; k < imgArray.length(); k++) {
										JSONObject object2 = imgArray
												.getJSONObject(k);
										Image image = gson
												.fromJson(object2.toString(),
														Image.class);
										// Log.d("image", "image Link " +
										// image.getSource());
										images.add(image);
									}
									String link = object1.getString("link");
									photos.get(j + object_counts[0]+object_counts[1] + temp)
											.setLink(link);
									String caption = object1
											.getString("caption");
									String photo_id = object1
											.getString("object_id");
									for (String string : CommonStatic.avoid_strings) {
										if (caption.contains(string)) {
											caption = caption.replace(string,
													"");
										}
									}
									Log.e("", "caption " + caption);
									Log.e("", "photo_id " + photo_id);
									if (datasource.isOpen())
										if (datasource.isAvailable(String
												.valueOf(photo_id)))
											photos.get(j + object_counts[0]+object_counts[1] + temp).isFavorite = true;
									photos.get(
											j + object_counts[0]+object_counts[1] + temp
													).setId(
											String.valueOf(photo_id));
									photos.get(
											j + object_counts[0]+object_counts[1] + temp
													).setName(
											caption);
									photos.get(
											j + object_counts[0]+object_counts[1] + temp
													).setImages(
											images);
									int created = object1.getInt("created");
									photos.get(
											j + object_counts[0]+object_counts[1] + temp
													)
											.setCreated(created);
									String album_id = object1
											.getString("album_object_id");
									photos.get(
											j + object_counts[0]+object_counts[1] + temp
													)
											.setAlbum_object_id(album_id);

								}
							} else {
								fbOffset[2] = -1;
							}
						}else if (nameobject.equals("photos"
								+ CommonStatic.arr[3])) {
							int temp_photo_count = fqlresult.length();
							if (temp_photo_count == 25) {
								for (int j = 0; j < temp_photo_count; j++) {
									JSONObject object1 = fqlresult
											.getJSONObject(j);
									if (j == 0) {
										String update_time = object1
												.getString("created");
										if (Long.valueOf(update_time) > update_time_value) {
											update_time_value = Long
													.valueOf(update_time);
										}
									}
									ArrayList<Image> images = new ArrayList<Image>();
									JSONArray imgArray = object1
											.getJSONArray("images");
									for (int k = 0; k < imgArray.length(); k++) {
										JSONObject object2 = imgArray
												.getJSONObject(k);
										Image image = gson
												.fromJson(object2.toString(),
														Image.class);
										// Log.d("image", "image Link " +
										// image.getSource());
										images.add(image);
									}
									String link = object1.getString("link");
									photos.get(j + object_counts[0]+object_counts[1]+object_counts[2] + temp)
											.setLink(link);
									String caption = object1
											.getString("caption");
									String photo_id = object1
											.getString("object_id");
									for (String string : CommonStatic.avoid_strings) {
										if (caption.contains(string)) {
											caption = caption.replace(string,
													"");
										}
									}
									Log.e("", "caption " + caption);
									Log.e("", "photo_id " + photo_id);
									if (datasource.isOpen())
										if (datasource.isAvailable(String
												.valueOf(photo_id)))
											photos.get(j + object_counts[0]+object_counts[1]+object_counts[2] + temp).isFavorite = true;
									photos.get(
											j + object_counts[0]+object_counts[1]+object_counts[2] + temp
													).setId(
											String.valueOf(photo_id));
									photos.get(
											j + object_counts[0]+object_counts[1]+object_counts[2] + temp
													).setName(
											caption);
									photos.get(
											j + object_counts[0]+object_counts[1]+object_counts[2] + temp
													).setImages(
											images);
									int created = object1.getInt("created");
									photos.get(
											j + object_counts[0]+object_counts[1]+object_counts[2] + temp
													)
											.setCreated(created);
									String album_id = object1
											.getString("album_object_id");
									photos.get(
											j + object_counts[0]+object_counts[1]+object_counts[2] + temp
													)
											.setAlbum_object_id(album_id);

								}
							} else {
								fbOffset[3] = -1;
							}
						}

						else if (nameobject.equals("commentlikeinfo"
								+ CommonStatic.arr[0])) {
							for (int j = 0; j < fqlresult.length(); j++) {
								JSONObject object1 = fqlresult.getJSONObject(j);
								JSONObject like_info = object1
										.getJSONObject("like_info");
								boolean user_like = like_info
										.getBoolean("user_likes");
								photos.get(j + temp).setIs_user_like(user_like);
								int like_count = like_info.getInt("like_count");
								JSONObject comment_info = object1
										.getJSONObject("comment_info");
								int comment_count = comment_info
										.getInt("comment_count");
								photos.get(j + temp).setLike_count(like_count);
								photos.get(j + temp).setComment_count(
										comment_count);
							}

						} else if (nameobject.equals("commentlikeinfo"
								+ CommonStatic.arr[1])) {
							for (int j = 0; j < fqlresult.length(); j++) {
								JSONObject object1 = fqlresult.getJSONObject(j);
								JSONObject like_info = object1
										.getJSONObject("like_info");
								boolean user_like = like_info
										.getBoolean("user_likes");
								photos.get(j + object_counts[0] + temp)
										.setIs_user_like(user_like);
								int like_count = like_info.getInt("like_count");
								JSONObject comment_info = object1
										.getJSONObject("comment_info");
								int comment_count = comment_info
										.getInt("comment_count");
								photos.get(j +  object_counts[0] + temp)
										.setLike_count(like_count);
								photos.get(j +  object_counts[0] + temp)
										.setComment_count(comment_count);
							}

						} else if (nameobject.equals("commentlikeinfo"
								+ CommonStatic.arr[2])) {
							for (int j = 0; j < fqlresult.length(); j++) {
								JSONObject object1 = fqlresult.getJSONObject(j);
								JSONObject like_info = object1
										.getJSONObject("like_info");
								boolean user_like = like_info
										.getBoolean("user_likes");
								photos.get(
										j + temp +  object_counts[0]
												+  object_counts[1])
										.setIs_user_like(user_like);
								int like_count = like_info.getInt("like_count");
								JSONObject comment_info = object1
										.getJSONObject("comment_info");
								int comment_count = comment_info
										.getInt("comment_count");
								photos.get(
										j + temp + object_counts[0]
												+  object_counts[1]).setLike_count(
										like_count);
								photos.get(
										j + temp + object_counts[0]
												+  object_counts[1])
										.setComment_count(comment_count);
							}

						}else if (nameobject.equals("commentlikeinfo"
								+ CommonStatic.arr[3])) {
							for (int j = 0; j < fqlresult.length(); j++) {
								JSONObject object1 = fqlresult.getJSONObject(j);
								JSONObject like_info = object1
										.getJSONObject("like_info");
								boolean user_like = like_info
										.getBoolean("user_likes");
								photos.get(
										j + temp + object_counts[0]
												+  object_counts[1]+object_counts[2])
										.setIs_user_like(user_like);
								int like_count = like_info.getInt("like_count");
								JSONObject comment_info = object1
										.getJSONObject("comment_info");
								int comment_count = comment_info
										.getInt("comment_count");
								photos.get(
										j + temp + object_counts[0]
												+  object_counts[1]+object_counts[2]).setLike_count(
										like_count);
								photos.get(
										j + temp + object_counts[0]
												+  object_counts[1]+object_counts[2])
										.setComment_count(comment_count);
							}

						}
					}
					if (!isFistRequest) {

						if (datasource.isOpen()) {
							String currentafter = datasource.checkAfter();
							if (currentafter != null) {
								datasource.updateBefore(currentafter,
										String.valueOf(update_time_value));
							} else {
								datasource.insertBefore(String
										.valueOf(update_time_value));
							}
						}
						isFistRequest = true;
					}
					
					for (int i = 0; i < object_counts.length; i++) {
						object_counts[i] = array.getJSONObject(i)
								.getJSONArray("fql_result_set").length();
						fbOffset[i]=object_counts[i];
					}
				}

			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Collections.sort(photos, new TimeComparator());

		if (photos.size() > 0) {
			if (viewPager.getAdapter() == null) {
				adapter = new PagerAdapter(photos, MainActivity.this);
				viewPager.setAdapter(adapter);
			} else {
				Log.e("", "notifidatasetchange ");
				viewPager.getAdapter().notifyDataSetChanged();
			}
			// if (is_add_temp_photo) {
			// try {
			// adapter.notifyDataSetChanged();
			// } catch (Exception e) {
			// // TODO: handle exception
			// Log.e("", "error " + e);
			// }
			// }
			viewPager.setPagingEnabled(true);
			is_add_temp_photo = false;
		}
		viewPager.setVisibility(View.VISIBLE);
		if (ll_loading.getVisibility() == View.VISIBLE) {
			Animation animation_left_right = AnimationUtils.loadAnimation(
					MainActivity.this, R.anim.slide_right_to_left);
			ll_loading.startAnimation(animation_left_right);
			ll_loading.setVisibility(View.GONE);
		}

	}

	@Override
	public void onResume() {
		super.onResume();
		uiLifecycleHelper.onResume();
		if (!datasource.isOpen()) {
			datasource.open();
		}
		for (int i = 0; i < photos.size(); i++) {
			if (datasource.isAvailable(photos.get(i).getId()))
				photos.get(i).isFavorite = true;
			else
				photos.get(i).isFavorite = false;
		}
		try {
			viewPager.getAdapter().notifyDataSetChanged();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiLifecycleHelper.onResume();
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
	}

	@Override
	public void onPause() {
		super.onPause();
		uiLifecycleHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiLifecycleHelper.onPause();
		if (datasource.isOpen()) {
			datasource.close();
		}
		imageLoader.clearDiscCache();
		imageLoader.clearMemoryCache();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiLifecycleHelper.onSaveInstanceState(outState);
	}

	public class GetBannerAsync extends AsyncTask<Void, Void, String> {
		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			String rs = HttpHelper.requestBanner(accestoken);
			Log.e("", "rs banner" + rs);
			return rs;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			Log.e("", "res get banner  " + result);
			if (!result.equals("")) {
				if (JsonUtil.getStatus(result)) {
					banner = JsonUtil.getBanner(result);
					if (banner != null) {
						llBanner.setVisibility(View.VISIBLE);
						DisplayImageOptions options1 = new DisplayImageOptions.Builder()
								.imageScaleType(
										ImageScaleType.EXACTLY_STRETCHED)
								.build();
						Log.e("", "begin load banner");
						imageLoader.displayImage(banner.images, imgBanner,
								options1);
					}
				}
			}

		}
	}

	public class GetPopUpAsync extends AsyncTask<Void, Void, String> {
		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			String rs = HttpHelper.requestPopUp(accestoken);
			Log.e("", "rs popup" + rs);
			return rs;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			Log.e("", "res get pop up " + result);
			if (!result.equals("")) {
				if (JsonUtil.getStatus(result)) {
					popup = JsonUtil.getBanner(result);
				}
			}
			new UpdateChecker().execute();

		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (popup != null) {
			AlertDialog.Builder builder = new Builder(MainActivity.this);
			builder.setTitle(getResources().getString(R.string.pop_up_title))
					.setMessage(popup.name)
					.setNegativeButton("OK",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method
									// stub
									dialog.dismiss();
									Intent intent1 = new Intent();
									intent1.setAction(Intent.ACTION_VIEW);
									intent1.addCategory(Intent.CATEGORY_BROWSABLE);
									intent1.setData(Uri.parse(popup.url));
									startActivity(intent1);
									finish();
								}
							})
					.setNeutralButton("Cancel",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
									finish();
								}
							});
			AlertDialog dialog = builder.create();
			;
			dialog.show();
		} else {
			super.onBackPressed();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e("", "get intent with flag stop service");
		Intent mIntent = new Intent(this, CheckNewPhotoService.class);
		mIntent.setAction(CheckNewPhotoService.ACTIOn);
		mIntent.putExtra("stop", true);
		startService(mIntent);
		try {
			PackageInfo info = getPackageManager().getPackageInfo(
					"com.gsmvn.ngamgaixinh", PackageManager.GET_SIGNATURES);
			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				Log.e("KeyHash:",
						Base64.encodeToString(md.digest(), Base64.DEFAULT));
			}
		} catch (NameNotFoundException e) {

		} catch (NoSuchAlgorithmException e) {

		}
		setContentView(R.layout.activity_main);
		setRecurringAlarm(this);
		if (isFBActive()) {
			Log.e("", "request me on create ");
			getUserIfvailable();
		}
		tracker = GoogleAnalytics.getInstance(this).getTracker(TRACKER_ID);
		initImageLoader();
		downloadUpdateProgress = new ProgressDialog(MainActivity.this);
		downloadUpdateProgress.setMessage(getResources().getString(
				R.string.downloadnewversion));
		downloadUpdateProgress.setIndeterminate(false);
		downloadUpdateProgress.setMax(100);
		downloadUpdateProgress
				.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		downloadUpdateProgress.setCancelable(false);
		fbOffset= new int[CommonStatic.arr.length];
		if (CommonUtils.checkNetworkAvaliable(this)) {
			String fqlQuery = "{";
			for (int i = 0; i < CommonStatic.arr.length; i++) {
				fqlQuery = fqlQuery.concat("'photos" + CommonStatic.arr[i]
						+ "':");
				fqlQuery = fqlQuery
						.concat("'select caption,images,created,object_id,link,created,album_object_id from photo where album_object_id="
								+ CommonStatic.arr_id[i]
								+ " limit 25 offset "
								+ fbOffset[i] + "',");
				fqlQuery = fqlQuery.concat("'commentlikeinfo"
						+ CommonStatic.arr[i] + "':");
				fqlQuery = fqlQuery
						.concat("'select like_info, comment_info from photo where album_object_id="
								+ CommonStatic.arr_id[i]
								+ " limit 25 offset "
								+ fbOffset[i] + "',");
			}
			fqlQuery = fqlQuery.concat("}");
			Log.e("", "fqlquery " + fqlQuery);
			Bundle params = new Bundle();
			params.putString("q", fqlQuery);
			Request request = new Request(null, "/fql", params, HttpMethod.GET,
					new Request.Callback() {

						@Override
						public void onCompleted(Response response) {
							// TODO Auto-generated method stub
							CommonUtils.writetoFile(response.toString(),
									MainActivity.this);
							initListPhoto(response);
						}
					});
			RequestAsyncTask asyncTask = new RequestAsyncTask(request);
			asyncTask.execute();
		} else
			showMessageDialog(R.string.error_connection,
					R.string.error_connection_msg);

		datasource = new DataSource(this);
		uiLifecycleHelper = new UiLifecycleHelper(this, callback);
		uiLifecycleHelper.onCreate(savedInstanceState);
		viewPager = (HackyViewPager) findViewById(R.id.view_pager);
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			private static final int offset_load_popup = 50;

			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				if (arg0 == photos.size() - 1) {
					if (!is_add_temp_photo) {
						Photo photo = new Photo();
						photo.setLike_count(0);
						photo.setLike_count(0);
						photo.setName("");
						ArrayList<Image> images = new ArrayList<Image>();
						Image img = new Image();
						img.setSource("http://dafda.com");
						images.add(img);
						photo.setImages(images);
						photos.add(photo);
						is_add_temp_photo = true;
						adapter.notifyDataSetChanged();
					} else {
						viewPager.setPagingEnabled(false);
						loadNextPageFB();
					}

				}
				if (arg0 % offset_load_popup == 0 && arg0 >= offset_load_popup) {
					if (popup != null && !isShowPopup) {
						AlertDialog.Builder builder = new Builder(
								MainActivity.this);
						builder.setTitle(
								getResources().getString(R.string.pop_up_title))
								.setMessage(popup.name)
								.setNegativeButton("OK",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												// TODO Auto-generated method
												// stub
												dialog.dismiss();
												Intent intent1 = new Intent();
												intent1.setAction(Intent.ACTION_VIEW);
												intent1.addCategory(Intent.CATEGORY_BROWSABLE);
												intent1.setData(Uri
														.parse(popup.url));
												startActivity(intent1);
											}
										})
								.setNeutralButton("Cancel",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												// TODO Auto-generated method
												// stub
												dialog.dismiss();
												isShowNetworkDialog = false;
											}
										});
						AlertDialog dialog = builder.create();
						dialog.show();
						isShowPopup = true;
					}
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
			}
		});

		ll_loading = (LinearLayout) findViewById(R.id.imgloading);
		llBanner = (RelativeLayout) findViewById(R.id.rlBanner);
		btnCloseBanner = (ImageButton) findViewById(R.id.closeBanner);
		btnCloseBanner.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				llBanner.setVisibility(View.GONE);
				handler.postDelayed(showBannerRunnable, time_to_show_banner);
			}
		});
		imgBanner = (ImageView) findViewById(R.id.imgBanner);
		imgBanner.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent1 = new Intent();
				intent1.setAction(Intent.ACTION_VIEW);
				intent1.addCategory(Intent.CATEGORY_BROWSABLE);
				Log.e("", "url banner " + banner.url);
				intent1.setData(Uri.parse(banner.url));
				startActivity(intent1);

			}
		});
		new GetAccessTokenAsync().execute();
	}

	private void createShortcut() {
		// TODO Auto-generated method stub
		if (!getSharedPreferences("congaixinh", 0).getBoolean(
				"install_shortcut", false)) {
			if (!appInstalledOrNot("com.appstoregp.vn")) {
				addShortcut();
				getSharedPreferences("congaixinh", 0).edit()
						.putBoolean("install_shortcut", true).commit();
			}
		}
		;
	}

	public void showMessageDialog(int title, int msg) {
		if (!isShowNetworkDialog) {
			AlertDialog.Builder builder = new Builder(this);
			builder.setTitle(getResources().getString(title))
					.setMessage(getResources().getString(msg))
					.setNegativeButton("OK",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
									finish();
								}
							});
			dialog = builder.create();
			dialog.show();
			isShowNetworkDialog = true;
		}
	}

	private StatusCallback callback = new StatusCallback() {

		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			// TODO Auto-generated method stub
			Log.e("", "error login facebook " + exception);
			if (state == SessionState.OPENED) {
				// dialog.dismiss();
				if (dialog != null && dialog.isShowing()
						&& !isShowNetworkDialog) {
					dialog.dismiss();
				}
				if (graphUser == null)
					getUserIfvailable();
			}
		}
	};

	private void getUserIfvailable() {
		Request requestme = Request.newMeRequest(Session.getActiveSession(),
				new GraphUserCallback() {

					@Override
					public void onCompleted(GraphUser user, Response response) {
						// TODO Auto-generated method stub
						Log.e("", "user res " + response);
						if (user != null) {
							graphUser = user;
							if (menu != null)
								onPrepareOptionsMenu(menu);
						}
					}
				});
		RequestAsyncTask asyncTask = new RequestAsyncTask(requestme);
		asyncTask.execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		this.menu = menu;
		return true;
	}

	MenuItem loginFBMenu;
	public ProgressDialog downloadUpdateProgress;

	private void loadNextPageFB() {
		Log.e("", "paging  " + paging);

		if (CommonUtils.checkNetworkAvaliable(this)) {
			// ll_loading.setVisibility(View.VISIBLE);
			// Animation animation_right_left = AnimationUtils.loadAnimation(
			// MainActivity.this, R.anim.slide_leff_to_right);
			// ll_loading.startAnimation(animation_right_left);
			// viewPager.setVisibility(View.INVISIBLE);
			String fqlQuery = "{";
			for (int i = 0; i < CommonStatic.arr.length; i++) {
				fqlQuery = fqlQuery.concat("'photos" + CommonStatic.arr[i]
						+ "':");
				int temp = -1;
				temp = fbOffset[i];
				fqlQuery = fqlQuery
						.concat("'select caption,images,created,object_id,link,created,album_object_id from photo where album_object_id="
								+ CommonStatic.arr_id[i]
								+ " limit 25 offset "
								+ temp + "',");
				fqlQuery = fqlQuery.concat("'commentlikeinfo"
						+ CommonStatic.arr[i] + "':");
				fqlQuery = fqlQuery
						.concat("'select like_info, comment_info from photo where album_object_id="
								+ CommonStatic.arr_id[i]
								+ " limit 25 offset "
								+ temp + "',");
			}
			fqlQuery = fqlQuery.concat("}");
			Log.e("", "fqlquery " + fqlQuery);
			Bundle params = new Bundle();
			params.putString("q", fqlQuery);
			Request request = new Request(null, "/fql", params, HttpMethod.GET,
					new Request.Callback() {

						@Override
						public void onCompleted(Response response) {
							// TODO Auto-generated method stub
							Log.e("", "res " + response.toString());
							initListPhoto(response);
						}
					});
			RequestAsyncTask asyncTask = new RequestAsyncTask(request);
			asyncTask.execute();
		} else
			showMessageDialog(R.string.error_connection,
					R.string.error_connection_msg);

	}

	public class PagerAdapter extends android.support.v4.view.PagerAdapter {
		ArrayList<Photo> photos;
		private Context context;

		public PagerAdapter(ArrayList<Photo> photos, Context context) {
			super();
			this.photos = photos;
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return photos.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return (arg0 == ((View) arg1));
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
			// TODO Auto-generated method stub
			Log.e("", "instantiateItem position " + position);
			View view = LayoutInflater.from(context).inflate(
					R.layout.item_viewpager, null);
			PhotoView img = (PhotoView) view.findViewById(R.id.img);
			TextView txtLike = (TextView) view.findViewById(R.id.txtLike);
			TextView txtComment = (TextView) view.findViewById(R.id.txtComment);
			final LinearLayout llLoadPhoto = (LinearLayout) view
					.findViewById(R.id.llloading);
			final TextView txtloadphoto = (TextView) view
					.findViewById(R.id.txtloadphoto);
			if (photos.get(position) != null) {
				if (photos.get(position) != null
						&& photos.get(position).getImages() != null)
					imageLoader.displayImage(photos.get(position).getImages()
							.get(0).getSource(), img, options,
							new ImageLoadingListener() {

								@Override
								public void onLoadingStarted() {
									// TODO Auto-generated method stub
									llLoadPhoto.setVisibility(View.VISIBLE);
									txtloadphoto.setText("Đang tải ảnh ...");
								}

								@Override
								public void onLoadingFailed(FailReason arg0) {
									// TODO Auto-generated method stub
									if (!is_add_temp_photo) {
										Photo photo = new Photo();
										photos.add(photo);
									}
								}

								@Override
								public void onLoadingComplete(Bitmap arg0) {
									// TODO Auto-generated method stub
									llLoadPhoto.setVisibility(View.GONE);
									txtloadphoto.setText("Đang tải ảnh ...");
								}

								@Override
								public void onLoadingCancelled() {
									// TODO Auto-generated method stub

								}
							});
				Log.e("", "like count "
						+ this.photos.get(position).getLikeInfo());
				txtLike.setText(this.photos.get(position).getLike_count() + "");
				txtComment.setText(this.photos.get(position).getComment_count()
						+ "");
				TextView photoName = (TextView) view
						.findViewById(R.id.photoName);
				photoName.setText(reBuildPhotoName(photos.get(position)
						.getName()));
				LinearLayout imgLike = (LinearLayout) view
						.findViewById(R.id.imageLike);
				imgLike.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (!Session.getActiveSession().isOpened()) {
							showLoginFaceBookDialog();
						} else {
							if (CommonUtils
									.checkNetworkAvaliable(MainActivity.this)) {
								Request request = new Request(Session
										.getActiveSession(), "/"
										+ photos.get(position).getId()
										+ "/likes", null, HttpMethod.POST,
										new Callback() {

											@Override
											public void onCompleted(
													Response response) {
												// TODO Auto-generated method
												// stub
												Log.e("", "res like "
														+ response.toString());
												GraphObject graphObject = response
														.getGraphObject();
												JSONObject json = graphObject
														.getInnerJSONObject();
												try {
													boolean state = json
															.getBoolean("FACEBOOK_NON_JSON_RESULT");
													if (state) {
														photos.get(position)
																.setIs_user_like(
																		true);
														Toast.makeText(
																MainActivity.this,
																"Bạn đã like thành công ảnh này",
																Toast.LENGTH_SHORT)
																.show();
													}
												} catch (JSONException e) {
													// TODO Auto-generated catch
													// block
													e.printStackTrace();
												}
											}
										});
								RequestAsyncTask asyncTask = new RequestAsyncTask(
										request);
								asyncTask.execute();
							} else
								showMessageDialog(R.string.error_connection,
										R.string.error_connection_msg);

						}
					}
				});
				LinearLayout imgComment = (LinearLayout) view
						.findViewById(R.id.imageComment);
				imgComment.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (!isFBActive()) {
							showLoginFaceBookDialog();
							// make request to the /me API
						} else {
							Intent intent = new Intent(MainActivity.this,
									CommentActivity.class);
							Log.e("", "photo_id "
									+ photos.get(position).getId());
							intent.putExtra("photo_id", photos.get(position)
									.getId());
							intent.putExtra("like_count", photos.get(position)
									.getLike_count());
							intent.putExtra("is_user_like", photos
									.get(position).isIs_user_like());
							intent.putExtra("album_id", photos.get(position)
									.getAlbum_object_id());
							startActivity(intent);
						}

					}
				});
				LinearLayout btnWallpaper = (LinearLayout) view
						.findViewById(R.id.wallpaper);

				final LinearLayout llFavorite = (LinearLayout) view
						.findViewById(R.id.llfavorite);

				final ImageView btnFavorite = (ImageView) view
						.findViewById(R.id.favorite);
				if (photos.get(position).isFavorite) {
					btnFavorite.setImageResource(R.drawable.deleteicon);
				} else {
					btnFavorite.setImageResource(R.drawable.heart);
				}

				btnWallpaper.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						AlertDialog.Builder builder = new Builder(
								MainActivity.this);
						builder.setTitle("Thông báo")
								.setMessage(
										"Bạn có muốn set ảnh này làm wallpaper ?")
								.setPositiveButton("Ok",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												// TODO Auto-generated method
												// stub
												new SetWallPaperAsync()
														.execute(new Integer[] { position });
												dialog.dismiss();
											}
										})
								.setNegativeButton("Cancel",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												// TODO Auto-generated method
												// stub
												dialog.dismiss();
											}
										});
						AlertDialog dialog = builder.create();
						dialog.show();

					}
				});
				llFavorite.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						datasource.open();
						if (!photos.get(position).isFavorite) {
							datasource.insert(photos.get(position).getId());
							photos.get(position).isFavorite = true;
							btnFavorite.setImageResource(R.drawable.deleteicon);
							Toast.makeText(MainActivity.this,
									"Đã đánh dấu ảnh", Toast.LENGTH_SHORT)
									.show();
						} else {
							datasource.delete(photos.get(position).getId());
							photos.get(position).isFavorite = false;
							btnFavorite.setImageResource(R.drawable.heart);
							Toast.makeText(MainActivity.this,
									"Đã bỏ đánh dấu ảnh", Toast.LENGTH_SHORT)
									.show();
						}

					}
				});
				final ImageView btnNext = (ImageView) view
						.findViewById(R.id.btnNext);
				final ImageView btnPrevious = (ImageView) view
						.findViewById(R.id.btnPrevious);
				if (position == 0)
					btnPrevious.setVisibility(View.GONE);
				if (photos.size() < 2) {
					btnNext.setVisibility(View.GONE);
					btnPrevious.setVisibility(View.GONE);
				}
				if (!isShowNavButton) {
					btnNext.setVisibility(View.GONE);
					btnPrevious.setVisibility(View.GONE);
				}
				btnNext.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						if (position == photos.size() - 1) {
							Log.e("", "load next page at position " + position);
							loadNextPageFB();
						} else {
							viewPager.setCurrentItem(
									viewPager.getCurrentItem() + 1, true);
						}

					}
				});
				img.setOnPhotoTapListener(new OnPhotoTapListener() {
					@TargetApi(Build.VERSION_CODES.HONEYCOMB)
					@SuppressLint("NewApi")
					@Override
					public void onPhotoTap(View view, float x, float y) {
						// TODO Auto-generated method stub
						if (!useFullscreen) {
							if (Build.VERSION.SDK_INT > 11)
								getActionBar().hide();
							btnNext.setVisibility(View.GONE);
							btnPrevious.setVisibility(View.GONE);
							isShowNavButton = false;
							for (int i = 0; i < viewPager.getChildCount(); i++) {
								View view1 = viewPager.getChildAt(i);
								view1.findViewById(R.id.btnNext).setVisibility(
										View.GONE);
								view1.findViewById(R.id.btnPrevious)
										.setVisibility(View.GONE);
							}
							getWindow().addFlags(
									WindowManager.LayoutParams.FLAG_FULLSCREEN);
							getWindow()
									.clearFlags(
											WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
							Toast.makeText(MainActivity.this,
									"Vuốt bằng 2 ngón tay để zoom ảnh",
									Toast.LENGTH_LONG).show();
							useFullscreen = true;
						} else {
							if (Build.VERSION.SDK_INT > 11)
								getActionBar().show();
							for (int i = 0; i < viewPager.getChildCount(); i++) {
								View view1 = viewPager.getChildAt(i);
								view1.findViewById(R.id.btnNext).setVisibility(
										View.VISIBLE);
								view1.findViewById(R.id.btnPrevious)
										.setVisibility(View.VISIBLE);
							}
							isShowNavButton = true;
							btnNext.setVisibility(View.VISIBLE);

							btnPrevious.setVisibility(View.VISIBLE);
							isShowNavButton = true;
							getWindow()
									.addFlags(
											WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
							getWindow().clearFlags(
									WindowManager.LayoutParams.FLAG_FULLSCREEN);
							useFullscreen = false;
						}
					}
				});

				btnPrevious.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						if (position != 0) {
							viewPager.setCurrentItem(
									viewPager.getCurrentItem() - 1, true);
						}
					}
				});
				RelativeLayout imgShareFaceBook = (RelativeLayout) view
						.findViewById(R.id.shareFB);
				final ProgressBar fbProgressBar = (ProgressBar) view
						.findViewById(R.id.progressFB);
				imgShareFaceBook.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (!isFBActive()) {
							showLoginFaceBookDialog();
							// make request to the /me API
						} else {
							fbProgressBar.setVisibility(View.VISIBLE);
							Session session = Session.getActiveSession();
							if (session != null) {
								JSONObject param = new JSONObject();
								try {
									if (CommonUtils
											.checkNetworkAvaliable(MainActivity.this)) {
										param.put("message",
												photos.get(position).getName());
										param.put("link", photos.get(position)
												.getLink());
										Request request = Request
												.newPostRequest(session,
														"/me/feed",
														GraphObject.Factory
																.create(param),
														new Request.Callback() {
															@Override
															public void onCompleted(
																	Response response) {
																Log.e("",
																		"res share fb "
																				+ response
																						.toString());
																if (response
																		.getError() == null) {
																	fbProgressBar
																			.setVisibility(View.GONE);
																	Toast.makeText(
																			MainActivity.this,
																			"Bạn đã share thành công",
																			Toast.LENGTH_SHORT)
																			.show();
																}
															}
														});
										request.executeAsync();
									} else
										showMessageDialog(
												R.string.error_connection,
												R.string.error_connection_msg);
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

							}
						}
					}
				});
			}
			view.setTag(this.photos.get(position));
			container.addView(view);

			return view;
		}
	}

	private boolean hasPublishPermission() {
		Session session = Session.getActiveSession();
		return session != null
				&& session.getPermissions().contains("publish_actions");
	}

	private void showLoginFaceBookDialog() {
		View view1 = LayoutInflater.from(MainActivity.this).inflate(
				R.layout.dialog, null);
		LoginButton ok = (LoginButton) view1.findViewById(R.id.authButton);
		ok.setOnErrorListener(new OnErrorListener() {

			@Override
			public void onError(FacebookException error) {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this, error.toString(), 2000)
						.show();
				Log.e("", error.toString());
			}
		});
		ArrayList<String> per = new ArrayList<String>();
		ArrayList<String> per1 = new ArrayList<String>();
		per.add("user_photos");
		per.add("publish_stream");

		ok.setPublishPermissions(per);
		AlertDialog.Builder buider = new Builder(MainActivity.this);
		buider.setTitle(getResources().getString(R.string.pop_up_title))
				.setView(view1);
		dialog = buider.create();
		dialog.show();

	}

	public class SetWallPaperAsync extends AsyncTask<Integer, Void, Void> {
		@Override
		protected Void doInBackground(Integer... arg0) {
			// TODO Auto-generated method stub
			int position = arg0[0];
			WallpaperManager myWallpaperManager = WallpaperManager
					.getInstance(getApplicationContext());
			myWallpaperManager.suggestDesiredDimensions(
					CommonUtils.getWidthScreen(MainActivity.this),
					CommonUtils.getHeightScreen(MainActivity.this));
			try {
				Log.e("", photos.get(position).getImages().get(0).getSource());
				InputStream in = new URL(photos.get(position).getImages()
						.get(0).getSource()).openStream();
				Bitmap bitmap = BitmapFactory.decodeStream(in);
				myWallpaperManager.setBitmap(bitmap);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			Toast.makeText(MainActivity.this, "Set WallPaper thành công",
					Toast.LENGTH_SHORT).show();
		}
	}

	private String reBuildPhotoName(String photoName) {
		return photoName.replaceAll("\\r\\n", "");
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		if (isFBActive()) {
			if (graphUser != null && menu != null)
				menu.getItem(0).getSubMenu().getItem(0)
						.setTitle("Chào bạn " + graphUser.getUsername());

		} else {
			menu.getItem(0).getSubMenu().getItem(0).setEnabled(true);
		}
		try {
			if (getSharedPreferences("congaixinh", 0).getBoolean(
					"notification", true)) {
				menu.getItem(0).getSubMenu().getItem(2)
						.setTitle("Báo ảnh mới (Đang Bật) ");
			} else {
				menu.getItem(0).getSubMenu().getItem(2)
						.setTitle("Báo ảnh mới (Đang Tắt) ");
			}

			if (getSharedPreferences("congaixinh", 0).getBoolean("floating",
					true)) {
				menu.getItem(0).getSubMenu().getItem(3)
						.setTitle("Hiển thị cửa sổ (Đang Bật) ");
			} else {
				menu.getItem(0).getSubMenu().getItem(3)
						.setTitle("Hiển thị cửa sổ (Đang Tắt) ");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.login:
			if (graphUser == null) {
				Log.e("", "graphUser " + graphUser);
				Session session = Session.getActiveSession().openActiveSession(
						this, true, callback);
			}
			return true;
		case R.id.favorite:
			Intent intent = new Intent(MainActivity.this,
					FavoriteActivity.class);
			startActivity(intent);
			return true;


		case R.id.notification:
			String msg = "";
			if (getSharedPreferences("congaixinh", 0).getBoolean(
					"notification", true)) {
				msg = "Bạn muốn tắt chức năng thông báo ảnh mới?";
			} else {
				msg = "Bạn muốn bật chức năng thông báo ảnh mới?";
			}

			AlertDialog.Builder builder1 = new Builder(MainActivity.this);
			builder1.setTitle("Cấu hình thông báo")
					.setMessage(msg)
					.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									if (getSharedPreferences("congaixinh", 0)
											.getBoolean("notification", true)) {
										getSharedPreferences("congaixinh", 0)
												.edit()
												.putBoolean("notification",
														false).commit();
										getSharedPreferences("congaixinh", 0)
												.edit()
												.putBoolean("floating", false)
												.commit();
									} else {
										getSharedPreferences("congaixinh", 0)
												.edit()
												.putBoolean("notification",
														true).commit();
										getSharedPreferences("congaixinh", 0)
												.edit()
												.putBoolean("floating", true)
												.commit();
									}
									onPrepareOptionsMenu(menu);
								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							});
			AlertDialog dialog1 = builder1.create();
			dialog1.show();
			return true;
		case R.id.dowload:
			Intent intent1 = new Intent();
			intent1.setAction(Intent.ACTION_VIEW);
			intent1.addCategory(Intent.CATEGORY_BROWSABLE);
			intent1.setData(Uri.parse(GOOGLE_LINK));
			startActivity(intent1);
			return true;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void initImageLoader() {
		imageLoader = ImageLoader.getInstance();
		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.ic_launcher).cacheInMemory()
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED).cacheOnDisc()
				.build();
		imageLoader.clearDiscCache();
		imageLoader.clearMemoryCache();
	}

	@Override
	public void onStart() {
		super.onStart();
		tracker.sendView("GaiXinhHome");
	}

	public class ShowCommentActivity extends AsyncTask<Integer, Void, Void> {
		ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			dialog = new ProgressDialog(MainActivity.this);
			dialog.setMessage("�?ang tải dữ liệu...");
			dialog.setCancelable(false);
			dialog.show();
		}

		@Override
		protected Void doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			int position = params[0];
			Intent intent = new Intent(MainActivity.this, CommentActivity.class);
			Photo photo = photos.get(position);
			Log.e("", "click view photo " + photo.getName());
			intent.putExtra("photo", photo);
			startActivity(intent);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			dialog.dismiss();
		}

	}

	private class DownloadFile extends AsyncTask<String, Integer, String> {
		@Override
		protected String doInBackground(String... sUrl) {
			try {
				URL url = new URL(sUrl[0]);
				URLConnection connection = url.openConnection();
				connection.connect();
				// this will be useful so that you can show a typical 0-100%
				// progress bar
				int fileLength = connection.getContentLength();

				// download the file
				InputStream input = new BufferedInputStream(url.openStream());
				File folder = new File(
						Environment.getExternalStorageDirectory()
								+ "/ConGaiXinh");
				boolean success = true;
				String filePath = null;
				if (!folder.exists()) {
					success = folder.mkdir();
				}
				if (success) {
					// Do something on success
					filePath = Environment.getExternalStorageDirectory()
							.getAbsolutePath() + "/ConGaiXinh/" + apk_name;
					Log.e("FilePath", filePath);
				} else {
					// Do something else on failure
					Toast.makeText(MainActivity.this,
							getResources().getString(R.string.couldntwitefile),
							Toast.LENGTH_SHORT).show();
					downloadUpdateProgress.dismiss();
				}

				OutputStream output = new FileOutputStream(filePath);

				byte data[] = new byte[1024];
				long total = 0;
				int count;
				while ((count = input.read(data)) != -1) {
					total += count;
					// publishing the progress....
					publishProgress((int) (total * 100 / fileLength));
					output.write(data, 0, count);
				}

				output.flush();
				output.close();
				input.close();
			} catch (Exception e) {
				downloadUpdateProgress.dismiss();
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			downloadUpdateProgress.show();
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			super.onProgressUpdate(progress);
			downloadUpdateProgress.setProgress(progress[0]);
			if (progress[0] == 100) {
				File folder = new File(
						Environment.getExternalStorageDirectory()
								+ "/ConGaiXinh");
				downloadUpdateProgress.dismiss();
				// start install latest update
				File fileLocation = new File(folder, apk_name);
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.fromFile(fileLocation),
						"application/vnd.android.package-archive");
				startActivity(intent);
			}
		}
	}

	public class UpdateChecker extends AsyncTask<Void, Void, Void> {
		String response;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			Log.e("RootActivity", "checking update..");
		}

		@Override
		protected Void doInBackground(Void... params) {
			String client = "android_girl";
			response = HttpHelper.checkUpdate(MainActivity.this, client);
			Log.e("RootActivity", "check update response" + response);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			try {
				JSONObject data = new JSONObject(response);
				boolean status = data.getBoolean(CommonStatic.STATUS);
				if (status) {
					JSONObject dataDetail = data.getJSONObject("data");
					boolean force_update = dataDetail
							.getBoolean("force_update");
					String title_message = "";
					String content_message = "";
					final String update_uri = dataDetail
							.getString("update_uri");
					JSONObject messageJson = dataDetail
							.getJSONObject("message");
					title_message = messageJson.getString("title");
					content_message = messageJson.getString("message");
					content_message = content_message.replaceAll("</br>", "");
					AlertDialog.Builder builder = new Builder(MainActivity.this);
					builder.setTitle(title_message);
					builder.setMessage(content_message);
					builder.setPositiveButton(
							getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									DownloadFile downloadFile = new DownloadFile();
									downloadFile.execute(update_uri);
									downloadUpdateProgress.show();
									downloadUpdateProgress
											.setOnCancelListener(new DialogInterface.OnCancelListener() {

												@Override
												public void onCancel(
														DialogInterface dialog) {
													// TODO Auto-generated
													// method stub

												}
											});
								}
							});
					if (force_update) {
						// go to link update & install the latest update
					} else {

						builder.setNegativeButton(
								getResources().getString(R.string.cancel),
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub
										dialog.dismiss();
									}
								});
					}
					builder.create();
					builder.setCancelable(false);
					builder.show();
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}

	}

	private void setRecurringAlarm(Context context) {
		// we know mobiletuts updates at right around 1130 GMT.
		// let's grab new stuff at around 11:45 GMT, inexactly
		Calendar calendar = Calendar.getInstance();
		Intent intent = new Intent(context, CheckNewPhotoReciver.class);
		intent.putExtra("action", "notification");
		PendingIntent penddIntent = PendingIntent.getBroadcast(context, 0,
				intent, PendingIntent.FLAG_CANCEL_CURRENT);
		AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		try {
			alarms.cancel(penddIntent);
		} catch (Exception e) {
			Log.e("", "AlarmManager update was not canceled. " + e.toString());
		}
		alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP,
				calendar.getTimeInMillis() + alarm_interval, alarm_interval,
				penddIntent);
	}

	private boolean appInstalledOrNot(String uri) {
		PackageManager pm = getPackageManager();
		boolean app_installed = false;
		try {
			pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
			app_installed = true;
		} catch (PackageManager.NameNotFoundException e) {
			app_installed = false;
		}
		Log.e("", "appInstalledOrNot " + app_installed);
		return app_installed;
	}

	Handler handler = new Handler();

	Runnable showBannerRunnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			llBanner.setVisibility(View.VISIBLE);
		}
	};

	int time_to_show_banner = 60 * 1000;

	private void addShortcut() {
		// Adding shortcut for MainActivity
		// on Home screen
		Intent shortcutIntent = new Intent(
				Intent.ACTION_VIEW,
				Uri.parse("https://play.google.com/store/apps/details?id=com.appstoregp.vn"));
		shortcutIntent.addCategory(Intent.CATEGORY_BROWSABLE);

		Intent addIntent = new Intent();
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "AppStoreVn ");
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				Intent.ShortcutIconResource.fromContext(
						getApplicationContext(), R.drawable.ic_launcher));

		addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
		getApplicationContext().sendBroadcast(addIntent);
	}

	private void removeShortcut() {

		// Deleting shortcut for MainActivity
		// on Home screen
		Intent shortcutIntent = new Intent(getApplicationContext(),
				MainActivity.class);
		shortcutIntent.setAction(Intent.ACTION_MAIN);

		Intent addIntent = new Intent();
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "HelloWorldShortcut");

		addIntent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
		getApplicationContext().sendBroadcast(addIntent);
	}

	public class GetAccessTokenAsync extends AsyncTask<Void, Void, String> {
		@Override
		protected String doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			return HttpHelper.getAccesToken();
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			Log.e("", "res get aceestoken " + result);
			if (!result.equals("")) {
				if (JsonUtil.getStatus(result)) {
					accestoken = JsonUtil.getAccessToken(result);
					new GetBannerAsync().execute();
					new GetPopUpAsync().execute();
				}
			}
		}
	}

}
